import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

class StreamBuilderPage extends StatefulWidget {
  const StreamBuilderPage({super.key});

  @override
  State<StreamBuilderPage> createState() => _StreamBuilderPageState();
}

class _StreamBuilderPageState extends State<StreamBuilderPage> {
  final future = Future.delayed(const Duration(seconds: 2), () => 43);
  final stream = Stream.periodic(const Duration(seconds: 2), (value) => value);

  // @override
  // void initState() {
  // super.initState();
  // future.then((value) => print("future value is $value"));
  // stream.listen((event) {
  //   print("stream:$event");
  // });
  // }

  Stream<int> counter() {
    return Stream.periodic(const Duration(seconds: 1), (value) {
      return value;
    });
  }

  buildStreamBuilder1() {
    return StreamBuilder(
        stream: counter(),
        builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              return const Center(
                child: Text("没有数据流..."),
              );
            case ConnectionState.waiting:
              return const Center(child: Text("WAITING: 等待数据流"));
            case ConnectionState.active:
              if (snapshot.hasError) {
                return Center(
                    child: Text("ACTIVE: 数据流活跃，异常: ${snapshot.error}"));
              } else {
                return Center(
                    child: Text("ACTIVE: 数据流活跃，数据: ${snapshot.data}"));
              }
            case ConnectionState.done:
              return const Center(child: Text("DONE: 数据流关闭"));
            default:
              throw "ConnectionState没有别的状态";
          }
        });
  }

  Stream<String> getTime() {
    return Stream.periodic(const Duration(seconds: 1), (count) {
      return "${DateTime.now().hour}-${DateTime.now().minute}-${DateTime.now().second}";
    });
  }

  buildStreamBuilder2() {
    return StreamBuilder(
        stream: getTime(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              return const Center(
                child: Text("没有数据流..."),
              );
            case ConnectionState.waiting:
              return const Center(child: Text("WAITING: 等待数据流"));
            case ConnectionState.active:
              if (snapshot.hasError) {
                return Center(
                    child: Text("ACTIVE: 数据流活跃，异常: ${snapshot.error}"));
              } else {
                return Center(
                    child: Text("ACTIVE: 数据流活跃，数据: ${snapshot.data}"));
              }
            case ConnectionState.done:
              return const Center(child: Text("DONE: 数据流关闭"));
            default:
              throw "ConnectionState没有别的状态";
          }
        });
  }

  // 定义一个类型为int的Stream
  // final _controller = StreamController<int>();
  final _controller = StreamController.broadcast();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller.stream.listen((event) {
      print("---event---$event");
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.close();
  }

  buildStreamBuilder3() {
    return Wrap(
      spacing: 20,
      children: [
        // 按钮点击后Stream让数字+1
        ElevatedButton(
            onPressed: () => _controller.add(1), child: const Text("add 1")),
        // 按钮点击后Stream让数字+2
        ElevatedButton(
            onPressed: () => _controller.add(2), child: const Text("add 2")),
        // 按钮点击后Stream让数字+2
        ElevatedButton(
            onPressed: () => _controller.add(3), child: const Text("add 3")),
        // 按钮点击后Stream让数字+2
        ElevatedButton(
            onPressed: () => _controller.add(4), child: const Text("add 4")),
        // 按钮点击后Stream让数字+2
        ElevatedButton(
            onPressed: () => _controller.add(5), child: const Text("add 5")),
        // 按钮点击后Stream释放出一个错误
        ElevatedButton(
            onPressed: () => _controller.addError("oops"),
            child: const Text("add error")),
        ElevatedButton(
            onPressed: () => _controller.close(), child: const Text("Close")),
        StreamBuilder(
            stream: _controller.stream
                .where((event) => event > 2)
                .map((event) => event * 2)
                .distinct(), // 去除重复的数据
            builder: (context, snapshot) {
              print("正在重新绘制StreamBuilder组件...");
              if (snapshot.connectionState == ConnectionState.done) {
                return const Text("数据流已关闭");
              }
              if (snapshot.hasError) return Text("${snapshot.error}");
              if (snapshot.hasData) return Text("${snapshot.data}");
              return const Center(
                child: CircularProgressIndicator(),
              );
            })
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text("StreamBuilder")),
        body: this.buildStreamBuilder3());
  }
}
